package com.example.function;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.adapter.AllCourseAdapter;
import com.example.database.DatabaseHelper;
import com.example.pojo.Course;
import com.example.student.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CourseFunction extends AppCompatActivity {
    private DatabaseHelper databaseHelper;

    private Spinner spinnerCollege, spinnerMajor, spinnerSemester, spinnerCourseType;
    private RecyclerView recyclerViewCourse;
    private List<Course> courseList = new ArrayList<>();
    private AllCourseAdapter courseAdapter;
    private HashMap<String, List<String>> collegeMajorMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_course_function);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        databaseHelper = new DatabaseHelper(this);

        // 初始化视图
        initViews();
        // 初始化 Spinner 数据
        initSpinnerData();
        // 初始化课程列表
        initCourseList();
        // 监听 Spinner 的选择事件
        setupSpinnerListeners();

        // 添加课程按钮点击事件
        FloatingActionButton fabAddCourse = findViewById(R.id.fab_add_course);
        fabAddCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CourseFunction.this, AddCourse.class);
                startActivity(intent);
            }
        });

    }

    private void setupSpinnerListeners() {
        spinnerCollege.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCollege = (String) parent.getItemAtPosition(position);
                //更新专业
                updateMajorSpinner(selectedCollege);
                filterCourses(selectedCollege,
                        (String) spinnerMajor.getSelectedItem(),
                        (String) spinnerSemester.getSelectedItem(),
                        (String) spinnerCourseType.getSelectedItem());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 监听专业 Spinner 的选择事件
        spinnerMajor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedMajor = (String) parent.getItemAtPosition(position);
                filterCourses((String) spinnerCollege.getSelectedItem(),
                        selectedMajor,
                        (String) spinnerSemester.getSelectedItem(),
                        (String) spinnerCourseType.getSelectedItem());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 监听学期 Spinner 的选择事件
        spinnerSemester.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedSemester = (String) parent.getItemAtPosition(position);
                filterCourses((String) spinnerCollege.getSelectedItem(),
                        (String) spinnerMajor.getSelectedItem(),
                        selectedSemester,
                        (String) spinnerCourseType.getSelectedItem());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 监听课程类型 Spinner 的选择事件
        spinnerCourseType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCourseType = (String) parent.getItemAtPosition(position);
                filterCourses((String) spinnerCollege.getSelectedItem(),
                        (String) spinnerMajor.getSelectedItem(),
                        (String) spinnerSemester.getSelectedItem(),
                        selectedCourseType);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    private void initSpinnerData() {
        // 初始化学院和专业数据
        collegeMajorMap = new HashMap<>();
        collegeMajorMap.put("计算机科学与技术", List.of("物联网工程", "计算机科学与技术", "网络安全"));
        collegeMajorMap.put("商学院", List.of("工商管理", "市场营销", "会计学"));
        collegeMajorMap.put("文学院", List.of("汉语言文学", "新闻学"));
        collegeMajorMap.put("理学院", List.of("数学与应用数学", "物理学", "化学"));
        collegeMajorMap.put("工程学院", List.of("机械工程", "电气工程", "土木工程"));
        collegeMajorMap.put("医学院", List.of("临床医学", "口腔医学", "药学"));
        collegeMajorMap.put("艺术学院", List.of("音乐学", "美术学", "设计学"));
        collegeMajorMap.put("法学院", List.of("法学", "知识产权", "国际法"));
        collegeMajorMap.put("教育学院", List.of("教育学", "心理学", "学前教育"));
        collegeMajorMap.put("农学院", List.of("农学", "园艺学", "植物保护"));

        // 初始化学院下拉框
        List<String> colleges = new ArrayList<>(collegeMajorMap.keySet());
        colleges.add(0, "请选择学院"); // 添加“请选择”选项
        ArrayAdapter<String> collegeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, colleges);
        collegeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCollege.setAdapter(collegeAdapter);

        // 初始化专业下拉框
        List<String> majors = new ArrayList<>();
        majors.add("请选择专业"); // 添加“请选择”选项
        ArrayAdapter<String> majorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, majors);
        majorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMajor.setAdapter(majorAdapter);

        // 初始化学期下拉框
        // 初始化学期下拉框
        List<String> semesters = new ArrayList<>();
        semesters.add("请选择学期"); // 添加“请选择学期”选项
        for (int i = 1; i <= 8; i++) {
            semesters.add(String.valueOf(i)); // 将学期转换为 String
        }
        ArrayAdapter<String> semesterAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, semesters);
        semesterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSemester.setAdapter(semesterAdapter);

        // 初始化课程类型下拉框
        List<String> courseTypes = new ArrayList<>();
        courseTypes.add("请选择课程类型"); // 添加“请选择”选项
        courseTypes.addAll(List.of("必修", "选修"));
        ArrayAdapter<String> courseTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, courseTypes);
        courseTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCourseType.setAdapter(courseTypeAdapter);
    }

    private void initViews() {
        spinnerCollege = findViewById(R.id.spinnerCollege);
        spinnerMajor = findViewById(R.id.spinnerMajor);
        spinnerSemester = findViewById(R.id.spinnerSemester);
        spinnerCourseType = findViewById(R.id.spinnerCourseType);
        recyclerViewCourse = findViewById(R.id.recyclerViewCourses);

        // 设置 RecyclerView
        recyclerViewCourse.setLayoutManager(new LinearLayoutManager(this));
        courseAdapter = new AllCourseAdapter(courseList, databaseHelper, this);
        recyclerViewCourse.setAdapter(courseAdapter);
    }

    private void initCourseList() {
        courseList.clear();
        List<Course> courses = databaseHelper.getCourses();
        courseList.addAll(courses);
        courseAdapter.notifyDataSetChanged();
    }

    private void filterCourses(String college, String major, String semester, String courseType) {
        // 如果选择的是“请选择”，则清空条件
        if ("请选择学院".equals(college)) {
            college = "";
        }
        if ("请选择专业".equals(major)) {
            major = "";
        }
        if ("请选择学期".equals(semester)) {
            semester = "";
        }
        if ("请选择课程类型".equals(courseType)) {
            courseType = "";
        }

        // 从数据库获取符合条件的课程
        courseList.clear();
        courseList.addAll(databaseHelper.getCoursesByFilter(college, major, semester, courseType));
        courseAdapter.notifyDataSetChanged();
    }
    /**
     * 更新专业 Spinner 的内容
     */
    private void updateMajorSpinner(String college) {
        // 获取专业列表
        List<String> majors = collegeMajorMap.get(college);
        if (majors == null) {
            majors = new ArrayList<>(); // 如果 majors 为 null，使用空列表
        }

        // 添加“请选择专业”选项
        List<String> majorList = new ArrayList<>();
        majorList.add("请选择专业"); // 添加“请选择”选项
        majorList.addAll(majors);

        // 设置适配器
        ArrayAdapter<String> majorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, majorList);
        majorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMajor.setAdapter(majorAdapter);

        // 设置默认选中第一项
        if (majorAdapter.getCount() > 0) {
            spinnerMajor.setSelection(0);
        }
    }
}
